package day8.race;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author oldliu
 * @since 1.0
 */
public class Player extends Thread {
    private String name;
    private int position=-1;
    private Race race;
    //private Lock lock=new ReentrantLock();

    public Player(String name,  Race race) {
        super(name);
        this.race = race;
    }

    @Override
    public void run() {
        int len=race.getMiles();
        while(len>0){
            len--;
            try {
                Thread.sleep((long) (Math.random()*5));
                if(len%100==0)
                    System.out.println(this.getName()+"剩余"+len+"米");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(this.getName()+"跑完了全程。。。");
//        try {
//            lock.lock();
//            this.position=race.getIndex();
//            race.inc();
//        } finally {
//            lock.unlock();
//        }

        synchronized (race){
           this.position=race.getIndex();
           race.inc();
       }
    }

    public int getPosition() {
        return position;
    }
}
